(function($){  

	$.fn.bertaEditable = {};
	$.fn.bertaEditable.defaults = {
		editor: 'Textline',			// editior plugin (see folder /js/editors/)
		variable: null,				// REST path to the variable
		context: '',				// context of the editor (can be 'entries', 'panel', ...)
		callbacks: {
			onChange: null,
			onSave: null,
			onRevert: null
		}
    };
	
	/**
	 * Turn on editability
	 * @param {Object} options
	 */
	$.fn.bertaEditableOn = function(optionsBase, editorParamsOverride) {
		
		// build main options before element iteration
		optionsBase = $.extend(true, {}, $.fn.bertaEditable.defaults, optionsBase);
		//options.callbacks.save = options.callbacks.save || save;

		// iterate and reformat each matched element
		return this.each(function() {
			$this = $(this);
			//console.debug($this.hasClass('x-editable-on'));
			if (!$this.hasClass('x-editable-on') && $this.hasClass('x-editable')) {
				
				// Read in plugin options from the element's data and override it, if necessary
				var options = $this.data('berta'),
					editorParams = {};
				
				// Get editor_params out of data attribute (if any) and pply editorParamsOverride overrides
				if(options.editor_params) {
					editorParams = options.editor_params;
					delete options.editor_params;
				}
				if(null !== editorParamsOverride && typeof editorParamsOverride == 'object') {
					editorParams = jQuery.extend(true, editorParams, editorParamsOverride);
				}
				
				options = jQuery.extend(true, {}, optionsBase, options);

				//$.log('bertaEditableOn', options, editorParams);

				// Create editor with manager
				Berta.EditorManager.instance().create($this, options.editor, options, editorParams);
			}
		});
	};
	
	/**
	 * Turn off editability
	 * @param {Object} doSave		Whether to save, if editing, before destroying
	 */
	$.fn.bertaEditableOff = function(doSave) {

		// iterate and reformat each matched element
		return this.each(function() {
			$this = $(this);
			
			Berta.EditorManager.instance().destroy($this, doSave);
			//Berta.Controller.execCommand('editorManager:destroy', $this, doSave);
		});
	};
	

	
	// ***********  PRIVATE  ***********************************************************************
    
	/*function onClick(event) {
		//$.log('jquery.editable: edito ' + event.data.options.editor);
		
		return false;
	}*/
    
      
})(jQuery);  